<template>
  <a-layout style="height: 100vh; background-color: #ffffff">
    <Navbar />
    <a-layout-content>
      <a-row type="flex" justify="center" style="margin-top: 100px">
        <a-col :span="12">
          <a-row>
            <!--文章列表-->
            <a-col :span="16">
              <template
                v-if="noteList && noteList.length > 0"
                v-for="(item, index) in noteList"
                :key="item.id"
              >
                <NoteItem :note="item" :index="index" @like="likeHandle" />
              </template>
              <a-skeleton :loading="loading" active></a-skeleton>
              <div style="text-align: center; padding: 20px" v-if="noData && !loading">
                没有更多数据了
              </div>
              <div style="text-align: center; padding: 20px; color: #999" v-if="noteList && noteList.length === 0 && !loading">
                暂无文章
              </div>
            </a-col>
            <a-col :span="1"></a-col>
            <!--右边栏-->
            <a-col :span="7">
              <BannerSider />
              <RecommendAuthor />
            </a-col>
          </a-row>
        </a-col>
      </a-row>
    </a-layout-content>
    <!--回到顶部-->
    <a-back-top>
      <div class="ant-back-top-inner">
        <Icon icon="ant-design:arrow-up-outlined" />
      </div>
    </a-back-top>
  </a-layout>
</template>

<script lang="ts" setup>
import { message } from "ant-design-vue";
import { Icon } from "@iconify/vue";

interface NoteItem {
  id: number;
  title: string;
  subTitle?: string;
  cover?: string;
  like: number;
  flag: boolean;
  uid: number;
  created_at: string;
  nickname: string;
}

interface ApiResponse<T = any> {
  code: number;
  msg: string;
  data: T;
}

interface NotesListData {
  list: NoteItem[];
}

useHead({
  title: "简书",
  meta: [
    {
      name: "description",
      content:
        "简书是一个优质的创作社区，在这里，你可以任性地创作，一篇短文、一张照片、一首诗、一幅画……我们相信，每个人都是生活中的艺术家，有着无穷的创造力。",
    },
    {
      name: "keywords",
      content:
        "简书,简书官网,图文编辑软件,简书下载,图文创作,创作软件,原创社区,小说,散文,写作,阅读",
    },
  ],
});
const page = ref(1);
const pageSize = ref(8);
const loading = ref(false);
const noData = ref(false);

// 获取文章列表数据
// 使用 server: true 进行 SSR，然后在客户端刷新以确保获取最新数据
const { data: noteListData } = await homeNotesFetch({
  method: "get",
  server: true, // SSR 时在服务端获取
  params: {
    page: page.value,
    pageSize: pageSize.value,
  },
  key: "noteListData", // 固定 key，Nuxt 会缓存
});

// 确保数据存在
const noteListResponse = noteListData.value as ApiResponse<NotesListData> | null;
if (!noteListResponse) {
  console.error("首页数据为空");
}

if (noteListResponse?.code === 1) {
  throw createError({ statusCode: 500, statusMessage: "获取文章列表失败" });
}

// 确保数据结构正确
if (noteListResponse?.code === 0 && !noteListResponse.data?.list) {
  console.error("首页数据结构异常:", noteListResponse);
  // 如果数据结构不对，初始化为空数组
  if (!noteListResponse.data) {
    (noteListResponse as ApiResponse<NotesListData>).data = { list: [] };
  } else if (!noteListResponse.data.list) {
    noteListResponse.data.list = [];
  }
}

// 初始加载完成，关闭加载状态
loading.value = false;

// 计算属性：获取文章列表
const noteList = computed(() => {
  const response = noteListData.value as ApiResponse<NotesListData> | null;
  return response?.data?.list || [];
});

// 上拉加载
const isBottom = () => {
  const scrollY = window.scrollY;
  const windowHeight = window.innerHeight;
  const pageHeight = document.documentElement.scrollHeight;
  return scrollY + windowHeight >= pageHeight;
};

// 防止重复添加事件监听器
let isLoading = false;
let scrollHandler: (() => void) | null = null;

const loadMore = () => {
  // 如果已经添加过监听器，先移除
  if (scrollHandler) {
    window.removeEventListener("scroll", scrollHandler);
  }
  
  // 创建新的滚动处理函数
  scrollHandler = () => {
    if (isBottom() && !isLoading && !noData.value) {
      isLoading = true;
      loading.value = true; // 开始加载更多
      page.value++;
      
      homeNotesFetch({
        method: "get",
        server: false,
        params: {
          page: page.value,
          pageSize: 5,
        },
        key: `loadMore-${page.value}`,
      }).then(({ data }) => {
        isLoading = false;
        loading.value = false; // 加载完成
        
        const response = data.value as ApiResponse<NotesListData> | null;
        if (response?.code === 0) {
          if (response.data.list.length === 0) {
            noData.value = true;
            return;
          }
          const currentData = noteListData.value as ApiResponse<NotesListData>;
          if (currentData?.data?.list) {
            currentData.data.list.push(...response.data.list);
          }
        } else {
          message.error(response?.msg || "获取文章列表失败");
        }
      }).catch((error) => {
        isLoading = false;
        loading.value = false;
        console.error("加载更多失败:", error);
        message.error("加载更多失败，请稍后重试");
      });
    }
  };
  
  // 添加滚动监听器
  window.addEventListener("scroll", scrollHandler);
};

const likeHandle = (like: number, index: number, flag: boolean) => {
  const currentData = noteListData.value as ApiResponse<NotesListData> | null;
  if (!currentData?.data?.list || !currentData.data.list[index]) return;
  
  if (flag) {
    like = like - 1;
    currentData.data.list[index].like = like;
    currentData.data.list[index].flag = false;
    return;
  }
  like = like + 1;
  currentData.data.list[index].like = like;
  currentData.data.list[index].flag = true;
};

// 刷新数据的函数，重置所有状态
const handleRefresh = async () => {
  if (!process.client) return;
  
  try {
    // 重置分页和状态
    page.value = 1;
    noData.value = false;
    loading.value = true;
    
    // 使用 $fetch 直接请求，避免 useFetch 的响应式问题
    const accessToken = useCookie("accessToken");
    const headers: Record<string, string> = {};
    if (accessToken.value) {
      headers.Authorization = `Bearer ${accessToken.value}`;
    }
    
    const freshData = await $fetch("/api/home/notes", {
      method: "GET",
      params: {
        page: 1,
        pageSize: pageSize.value,
      },
      headers,
    });
    
    // 等待 Vue 响应式更新
    await nextTick();
    
    // 检查数据是否存在
    if (!freshData) {
      console.error("刷新失败，响应数据为空");
      message.error("服务器响应为空，请稍后重试");
      return;
    }
    
    const freshResponse = freshData as ApiResponse<NotesListData>;
    if (freshResponse?.code === 0) {
      // 直接替换数据，而不是合并
      if (freshResponse.data && Array.isArray(freshResponse.data.list)) {
        noteListData.value = freshResponse as any;
      } else {
        console.error("刷新后数据结构异常:", freshResponse);
        // 确保数据结构正确
        const currentData = noteListData.value as ApiResponse<NotesListData>;
        if (!currentData?.data) {
          (currentData as ApiResponse<NotesListData>).data = { list: [] };
        } else {
          currentData.data.list = [];
        }
      }
    } else {
      console.error("刷新失败，响应:", freshResponse);
      if (freshResponse?.msg) {
        message.error(freshResponse.msg);
      } else {
        message.error("刷新数据失败");
      }
    }
  } catch (error) {
    console.error("刷新数据时出错:", error);
    message.error("刷新数据失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 在客户端挂载时刷新数据并设置滚动监听
onMounted(async () => {
  if (process.client) {
    // 刷新数据，这样浏览器可以看到请求
    await handleRefresh();
    
    // 设置滚动加载更多
    loadMore();
  }
});

// 监听路由变化，当返回首页时刷新数据
const route = useRoute();
watch(() => route.path, async (newPath, oldPath) => {
  if (newPath === '/' && oldPath && oldPath !== '/') {
    // 从其他页面返回首页，刷新数据并重置状态
    if (process.client) {
      await handleRefresh();
      // 重新设置滚动加载（因为页面可能被重新渲染）
      loadMore();
    }
  }
}, { immediate: false });

// 组件卸载时移除事件监听器
onUnmounted(() => {
  if (scrollHandler) {
    window.removeEventListener("scroll", scrollHandler);
    scrollHandler = null;
  }
});
</script>

<style lang="scss" scoped>
:deep(.ant-back-top) {
  bottom: 100px;
}
.ant-back-top-inner {
  height: 40px;
  width: 40px;
  line-height: 40px;
  border-radius: 4px;
  border: 1px solid #e05344;
  color: #e05344;
  text-align: center;
  font-size: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
